package com.groupbuying.currency.consumer.mq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.groupbuying.currency.consumer.connector.CustomerFeign;
import com.groupbuying.currency.consumer.connector.PayInfoFeign;
import com.groupbuying.currency.consumer.connector.SysconfigFeign;
import com.groupbuying.currency.consumer.constants.CommonConstants;
import com.groupbuying.currency.consumer.constants.CurrencyCustomerLogEnumConstants;
import com.groupbuying.currency.consumer.constants.CurrencyCustomerLogSearchConstants;
import com.groupbuying.currency.consumer.domain.CurrencyCustomerDO;
import com.groupbuying.currency.consumer.domain.CurrencyCustomerLogDO;
import com.groupbuying.currency.consumer.dto.wx.currency.add.CurAddNotifJsonData;
import com.groupbuying.currency.consumer.dto.wx.currency.add.data.*;
import com.groupbuying.currency.consumer.service.CurrencyCustomerLogService;
import com.groupbuying.currency.consumer.service.CurrencyCustomerService;
import com.groupbuying.currency.consumer.service.CurrencyRebackService;
import com.groupbuying.currency.consumer.utils.*;
import com.groupbuying.currency.consumer.utils.apiresult.ApiResult;
import com.groupbuying.currency.consumer.utils.apiresult.ApiResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @auter miaozhenfei
 * @date 2019/9/4 15:47
 */
@Component
public class CurrencyPayResult {
    public static final Logger LOGGER = LoggerFactory.getLogger(CurrencyPayResult.class);
    @Autowired
    private CurrencyCustomerService currencyCustomerService;

    @Autowired
    private WeiXinUtils weiXinUtils;

    @Autowired
    private HttpClientUtils httpClientUtils;

    @Autowired
    private PayInfoFeign payInfoFeign;

    @Autowired
    private CustomerFeign customerFeign;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private CurrencyRebackService currencyRebackService;

    @Autowired
    private CurrencyCustomerLogService currencyCustomerLogService;

    @Autowired
    private SysconfigFeign sysconfigFeign;

    public boolean currencyAddResult(Map<String, Object> result) {
        try {
            //线上支付成功，支付成功总积分
            LOGGER.info("积分增加的参数是：{}", result);
            /* 处理tag为CURRENCY_ADD（积分增加的消息） */
            /* 获取支付ID */
            String payId = result.get("payId").toString();
            /* 获取积分账户ID */
            String customerId = result.get("customerId").toString();
            /* 获取消费金额 */
            BigDecimal consumptionAmount = Object2BigDecimal
                    .getBigDecimal(result.get("consumptionAmount"));
            /* 获取消费返积分率 */
            BigDecimal backCurrencyRatio = Object2BigDecimal
                    .getBigDecimal(result.get("backCurrencyRatio"));

            /* 2. 消息去重，防止重复消费 */
            if (redisUtils.isHasKey("currencyChangePayId_" + payId)) {
                return false;
            }

            /* 3. 非积分消费增加积分并返回更新后的对象 */
            CurrencyCustomerDO currencyCustomerDO = currencyCustomerService
                    .addCurrencyByOnlineConsumption(customerId, payId, consumptionAmount,
                            backCurrencyRatio);

            /* 接2消息去重，防止重复消费 */
            redisUtils.setKey("currencyChangePayId_" + payId, "currencyChangePayId");

            LOGGER.info("redis消息缓存key-value:{}{}", payId, redisUtils.getValue(payId));
            LOGGER.info("获取payId:{},customerId:{},consumptionAmount:{},返积分率:{},currencyCustomerDO账户积分余额:{}", payId, customerId, consumptionAmount, backCurrencyRatio, currencyCustomerDO.getUseCurrency());
            /* -------------------------------------------------------------------------------------------------------------- */

            /* 非积分消费增加积分后，微信通知用户积分变动情况 */
            /* 1. 获取微信调用access_token */
            Map<String, String> map = payInfoFeign.getInfoForCurrencyWeChatRemind(payId);
            String orderId = map.get("orderId");
            String shopName = map.get("shopName");
            String payTime = map.get("payTime");
            String payMoney = map.get("payMoney");
            String formId = map.get("formId");
            String openId = customerFeign.getOpenidByCustomerId(customerId);
//            String accessToken = weiXinUtils.getAccessToken();
            Map<String, Object> miniParams = new HashMap<>();
            miniParams.put("indicate","youdianproductor");
            miniParams.put("openId", openId);
            miniParams.put("templateId", "081kV2dQOvyo1pamufAgutV8v1wKZYDYmpVHCwc9gUw");
            miniParams.put("formId", formId);
            Map<String, Object> data = new HashMap<>();
            data.put("keyword1", shopName);
            data.put("keyword2", orderId);
            data.put("keyword3", payMoney);
            data.put("keyword4", "+" + consumptionAmount.multiply(backCurrencyRatio).divide(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_DOWN) + "积分");
            data.put("keyword5", currencyCustomerDO.getUseCurrency().setScale(2, BigDecimal.ROUND_DOWN) + "积分");
            data.put("keyword6", payTime);
            miniParams.put("data", JSON.toJSON(data));
            LOGGER.info("拼装消息：{}",miniParams );
            ApiResult respResult = sysconfigFeign.doWechatMiniTemplateSend(miniParams);
            if (ApiResultCode.SUCCESS.code().equals(respResult.getCode())) {
                LOGGER.info("积分增加消息发送成功");
            } else {
                LOGGER.info("积分增加消息发送失败");
            }
        }catch (Exception e){
            LOGGER.error("积分增加出现错误，原因：{}",e.getMessage());
        }
            return true;
        //            LOGGER.info("获取accessToken:{}",accessToken);
//            /* 2. 拼接微信小程序的发送地址 */
//            String sendCurChangeUrl =
//                    "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send"
//                            + "?access_token=" + accessToken;
//
//            /* 3. 装配微信小程序的发送包体 */
//
//
//            LOGGER.info("获取包体信息为:{}{}{}{}{}{}",orderId,shopName,payTime,payMoney,formId,openiId);
//            CurAddNotifJsonData curAddNotifJsonData = new CurAddNotifJsonData();
//            curAddNotifJsonData.setTouser(openiId);
//            curAddNotifJsonData.setFormId(formId);
//            curAddNotifJsonData
//                    .setTemplateId("081kV2dQOvyo1pamufAgutV8v1wKZYDYmpVHCwc9gUw");
//            Keyword1 keyword1 = new Keyword1();
//            Keyword2 keyword2 = new Keyword2();
//            Keyword3 keyword3 = new Keyword3();
//            Keyword4 keyword4 = new Keyword4();
//            Keyword5 keyword5 = new Keyword5();
//            Keyword6 keyword6 = new Keyword6();
//            keyword1.setValue(shopName);
//            keyword2.setValue(orderId);
//            keyword3.setValue(payMoney);
//            keyword4.setValue("+" + consumptionAmount.multiply(backCurrencyRatio).divide(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_DOWN) + "积分");
//            keyword5.setValue(currencyCustomerDO.getUseCurrency().setScale(2,BigDecimal.ROUND_DOWN) + "积分");
//            keyword6.setValue(payTime);
//            Data data = new Data(keyword1, keyword2, keyword3, keyword4, keyword5, keyword6);
//            LOGGER.info("获取订单通知消息为:{}",data);
//            curAddNotifJsonData.setData(data);
//
//            JSONObject jsonObject = (JSONObject) JSON.toJSON(curAddNotifJsonData);
//            jsonObject.put("form_id", jsonObject.getString("formId"));
//            jsonObject.put("page", "pages/home/index/index");
//            jsonObject.put("template_id", jsonObject.getString("templateId"));
//            jsonObject.remove("formId");
//            jsonObject.remove("templateId");
//
//            /* 4. 向微信服务器发送post请求，发送积分变动信息给用户 */
//            JSONObject returnJsonObject = httpClientUtils.doPostSendJson(sendCurChangeUrl, jsonObject);
//            LOGGER.info("消息发送返回结果:{}",returnJsonObject);
//            String errmsg = returnJsonObject.getString("errmsg");
//            LOGGER.info("错误信息:{}",errmsg);
//            String errcode = returnJsonObject.getString("errcode");
//            LOGGER.info("错误码:{}",errcode);
//            if (!errcode.equals("0") || !errmsg.equals("ok")) {
//                LOGGER.error("发送积分变动消息失败!");
//            }else{
//                LOGGER.info("消息通知成功");
//            }
//            LOGGER.info("消息通知完成");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return true;
    }

    //线上支付退款，减积分
    public boolean onlinePayRebackCurrency(Map<String, Object> result){
        try {
            //线上支付成功，支付成功总积分
            LOGGER.info("积分增加的参数是：{}",result);
            /* 处理tag为CURRENCY_ADD（积分增加的消息） */
            /* 获取支付ID */
            String payId = result.get("payId").toString();
            /* 获取积分账户ID */
            String customerId = result.get("customerId").toString();

            /* 2. 消息去重，防止重复消费 */
            if (redisUtils.isHasKey("onlinePayRebackCurrency_" + payId)) {
                return false;
            }

            Map searchMap = new HashMap();
            searchMap.put(CurrencyCustomerLogSearchConstants.SEARCH_PAYID,payId);
            searchMap.put(CurrencyCustomerLogSearchConstants.SEARCH_CUSTOMERID,customerId);
            searchMap.put(CurrencyCustomerLogSearchConstants.SEARCH_DELFLAG,CommonConstants.COMMON_FLAG_UNDEL);
            searchMap.put(CurrencyCustomerLogSearchConstants.SEARCH_CURRENCYTYPE,CurrencyCustomerLogEnumConstants.ENUM_CURRENCYTYPE_ADD);
            List<CurrencyCustomerLogDO> list_log = currencyCustomerLogService.list(searchMap);

            if(list_log == null || list_log.size() == 0){
                return false;
            }

            /* 接2消息去重，防止重复消费 */
            redisUtils.setKey("onlinePayRebackCurrency_" + payId, "currencyChangePayId");

            CurrencyCustomerLogDO currencyCustomerLogDO = list_log.get(0);
            /* 3. 非积分消费增加积分并返回更新后的对象 */
            return currencyRebackService.doRebackWithOnlinePay(currencyCustomerLogDO ,customerId, payId);


            //formId 已经使用，无需发送通知


            /* 非积分消费增加积分后，微信通知用户积分变动情况 */
            /* 1. 获取微信调用access_token */
            //String accessToken = weiXinUtils.getAccessToken();
//            LOGGER.info("获取accessToken:{}",accessToken);
//            /* 2. 拼接微信小程序的发送地址 */
//            String sendCurChangeUrl =
//                    "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send"
//                            + "?access_token=" + accessToken;
//
//            /* 3. 装配微信小程序的发送包体 */
//            Map<String, String> map = payInfoFeign.getInfoForCurrencyWeChatRemind(payId);
//            String orderId = map.get("orderId");
//            String shopName = map.get("shopName");
//            String payTime = map.get("payTime");
//            String payMoney = map.get("payMoney");
//            String formId = map.get("formId");
//            String openiId = customerFeign.getOpenidByCustomerId(customerId);
//            LOGGER.info("获取包体信息为:{}{}{}{}{}{}",orderId,shopName,payTime,payMoney,formId,openiId);
//            CurAddNotifJsonData curAddNotifJsonData = new CurAddNotifJsonData();
//            curAddNotifJsonData.setTouser(openiId);
//            curAddNotifJsonData.setFormId(formId);
//            curAddNotifJsonData
//                    .setTemplateId("081kV2dQOvyo1pamufAgutV8v1wKZYDYmpVHCwc9gUw");
//            Keyword1 keyword1 = new Keyword1();
//            Keyword2 keyword2 = new Keyword2();
//            Keyword3 keyword3 = new Keyword3();
//            Keyword4 keyword4 = new Keyword4();
//            Keyword5 keyword5 = new Keyword5();
//            Keyword6 keyword6 = new Keyword6();
//            keyword1.setValue(shopName);
//            keyword2.setValue(orderId);
//            keyword3.setValue(payMoney);
//
//            keyword4.setValue("+" + consumptionAmount.multiply(backCurrencyRatio).divide(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_DOWN) + "积分");
//            keyword5.setValue(currencyCustomerDO.getUseCurrency().setScale(2,BigDecimal.ROUND_DOWN) + "积分");
//
//            keyword6.setValue(payTime);
//            Data data = new Data(keyword1, keyword2, keyword3, keyword4, keyword5, keyword6);
//            LOGGER.info("获取订单通知消息为:{}",data);
//            curAddNotifJsonData.setData(data);
//
//            JSONObject jsonObject = (JSONObject) JSON.toJSON(curAddNotifJsonData);
//            jsonObject.put("form_id", jsonObject.getString("formId"));
//            jsonObject.put("page", "pages/home/index/index");
//            jsonObject.put("template_id", jsonObject.getString("templateId"));
//            jsonObject.remove("formId");
//            jsonObject.remove("templateId");
//
//            /* 4. 向微信服务器发送post请求，发送积分变动信息给用户 */
//            JSONObject returnJsonObject = httpClientUtils.doPostSendJson(sendCurChangeUrl, jsonObject);
//            LOGGER.info("消息发送返回结果:{}",returnJsonObject);
//            String errmsg = returnJsonObject.getString("errmsg");
//            LOGGER.info("错误信息:{}",errmsg);
//            String errcode = returnJsonObject.getString("errcode");
//            LOGGER.info("错误码:{}",errcode);
//            if (!errcode.equals("0") || !errmsg.equals("ok")) {
//                LOGGER.error("发送积分变动消息失败!");
//            }else{
//                LOGGER.info("消息通知成功");
//            }
//            LOGGER.info("消息通知完成");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return true;
    }
}
